#include "udprecvwidget.h"
#include "ui_udprecvwidget.h"

UdpRecvWidget::UdpRecvWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UdpRecvWidget)
{
    ui->setupUi(this);

    isRecieved = false;
}

UdpRecvWidget::~UdpRecvWidget()
{
    delete ui;
}

void UdpRecvWidget::on_pushButtonRecv_clicked()
{
    if(!isRecieved){
        isRecieved = true;
        ui->pushButtonRecv->setText("Stop");
        udpSocket = new QUdpSocket(this);
        connect(udpSocket, SIGNAL(readyRead()), this, SLOT(slotReadData()));


        quint16 port = 9998;
        bool ok = udpSocket->bind(port);
        if(!ok)
        {
            QMessageBox::warning(this, "Failure", udpSocket->errorString());
            return ;
        }
        else
        {
            //char recv_buf[4096];
            qDebug("Recieve file ...");
            //udp
        }
        ui->textEdit->clear();
    }
    else{
        isRecieved = false;
        ui->pushButtonRecv->setText("Recieve");
        udpSocket->close();
    }
}

void UdpRecvWidget::slotReadData()
{
    while(udpSocket->hasPendingDatagrams())
    {
        //QByteArray datagram;
        char recv_buf[4096];
        QHostAddress host;
        quint16 port;

        //datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(recv_buf, sizeof(recv_buf), &host, &port);
        QString temp(recv_buf);
        //file(ui->lineEditFilename->text());
        //file->open(QIODevice::WriteOnly);

        file = new QFile(ui->lineEditFilename->text());
        bool ok = file->open(QIODevice::WriteOnly | QIODevice::Truncate);
        if(!ok)
        {
           QMessageBox::warning(this,NULL,file->errorString());
           return;
        }
        QDataStream out(file);
        out << temp;

        file->write(ui->textEdit->toPlainText().toLocal8Bit());
        file->flush();
        file->close();

        //udpSocket->writeDatagram(datagram, datagram.size(), host, port);
        qDebug() << host.toString() + "[" + QString::number(port) + "]";
    }
}
